package org.easyframework.bad.core;

import java.io.File;
import java.util.Vector;

public class CLTask {

	private String executable;
	private File workingDir;

	private Vector<Arg> args = new Vector<CLTask.Arg>();

	public String[] getCommand() {
		final String[] args = getArguments();
		if (executable == null) {
			return args;
		}
		final String[] result = new String[args.length + 1];
		result[0] = executable;
		System.arraycopy(args, 0, result, 1, args.length);
		return result;
	}

	public String[] getArguments() {
		final Vector<String> result = new Vector<String>(args.size() * 2);
		for (int i = 0; i < args.size(); i++) {
			final Arg arg = args.elementAt(i);
			final String[] s = arg.getParts();
			if (s != null) {
				for (final String value : s) {
					result.addElement(value);
				}
			}
		}

		final String[] res = new String[result.size()];
		result.copyInto(res);
		return res;
	}

	public void addArg(final String value) {
		Arg arg = new Arg(value);

		args.add(arg);
	}

	public void setExecutable(String executable) {
		this.executable = executable;
	}

	public void setWorkingDirectory(String path) {
		if (path != null) {
			File dir = new File(path);
			workingDir = dir;
		} else {
			workingDir = new File(System.getProperty("user.dir"));
		}
	}

	protected File getWorkingDir() {
		return workingDir;
	}

	public String getExecutable() {
		return executable;
	}

	static class Arg {
		private String[] parts;

		public Arg(String value) {
			setValue(value);
		}

		public void setValue(String value) {
			parts = new String[] { value };
		}

		/**
		 * @return the parts this Argument consists of.
		 */
		public String[] getParts() {
			return parts;
		}
	}
}
